package com.hydl.power.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.hydl.power.mapper.*;
import com.hydl.power.netty.Utils.ConvertCode;
import com.hydl.power.netty.model.SmartIotpower;
import com.hydl.power.pojo.*;
import com.hydl.power.service.OrderDeliveryService;
import com.hydl.power.service.PowerDataService;
import com.hydl.power.utils.Resp;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
@Service
public class PowerDataServiceImpl implements PowerDataService {

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private PowerdataMapper powerdataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private OrderDeliveryService orderDeliveryService;

    @Autowired
    private OrderDeliveryMapper orderDeliveryMapper;

    @Autowired
    private IncomingCabinetMapper incomingCabinetMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TemperatureDeviceMapper temperatureDeviceMapper;

    @Autowired
    private TemperatureDataMapper temperatureDataMapper;

//    @Autowired
//    private AlarmRecordMapper AlarmRecodMapper;

    @Override
    public Resp AddPowerData(SmartIotpower iot) {
        int res=0;
        Powerdata powerdata = new Powerdata();
        Device device=null;
            if (iot != null) {
                //设备号,int类型转换为16进制,两个byte字节组成byte数组转化为16进制
                byte[] deviceTypeAndcode = new byte[2];
                deviceTypeAndcode[0] = iot.getDeviceType();
                deviceTypeAndcode[1] = iot.getVendorCode();
                String deviceId = ConvertCode.intToHexString(iot.getDeviceid(), 4) + ConvertCode.bytes2HexString(deviceTypeAndcode);

//            String iemi = "866671046218187";
                float Ia = iot.getIa();
                float Ib = iot.getIb();
                float Ic = iot.getIc();
                //A相电压
                float Ua = iot.getUa();
                float Ub = iot.getUb();
                float Uc = iot.getUc();
                //ab相电压
                float Uab = iot.getUab();
                float Ubc = iot.getUbc();
                float Uca = iot.getUca();
                //A相有功总功率
                float Pa = iot.getPA();
                float Pb = iot.getPB();
                float Pc = iot.getPC();
                float Pt = iot.getPT();
                //A相无功总功率
                float Pan = iot.getPAn();
                float Pbn = iot.getPBn();
                float Pcn = iot.getPCn();
                float Ptn = iot.getPTn();
                //A相功率因数PAf,除以1000
                float Paf = iot.getPAf() / 1000;
                float Pbf = iot.getPBf() / 1000;
                float Pcf = iot.getPCf() / 1000;
                //总功率因数PTf
                float ptf = iot.getPTf() / 1000;
                float Pain = iot.getPAin();
                float Pbin = iot.getPBin();
                float Pcin = iot.getPCin();
                //总现在功率
                float Ptin = iot.getPTin() / 1000;
                //电网频率
                float frequency = iot.getFrequency() / 100;
                float combinedActiveTipEnergy = iot.getCombinedActiveTipEnergy();
                float forwardActiveTotalElectricalEnergy = iot.getForwardActiveTotalElectricalEnergy();
                float totalReverseActiveEnergy = iot.getTotalReverseActiveEnergy();

                powerdata.setDeviceid(deviceId);
//            powerdata.setIemi(iemi);
                powerdata.setIa(Ia);
                powerdata.setIb(Ib);
                powerdata.setIc(Ic);
                powerdata.setUa(Ua);
                powerdata.setUb(Ub);
                powerdata.setUc(Uc);
                powerdata.setUab(Uab);
                powerdata.setUbc(Ubc);
                powerdata.setUca(Uca);
                powerdata.setPa(Pa);
                powerdata.setPb(Pb);
                powerdata.setPc(Pc);
                powerdata.setPt(Pt);
                powerdata.setPan(Pan);
                powerdata.setPbn(Pbn);
                powerdata.setPcn(Pcn);
                powerdata.setPtn(Ptn);
                powerdata.setPaf(Paf);
                powerdata.setPbf(Pbf);
                powerdata.setPcf(Pcf);
                powerdata.setPtf(ptf);
                powerdata.setPain(Pain);
                powerdata.setPbin(Pbin);
                powerdata.setPcin(Pcin);
                powerdata.setPtin(Ptin);
                powerdata.setFrequency(frequency);
                powerdata.setFrequency(frequency);
                powerdata.setFrequency(frequency);
                powerdata.setFrequency(frequency);
                powerdata.setCreatetime(new Date());
                powerdata.setCombinedActiveTipEnergy(combinedActiveTipEnergy);
                powerdata.setForwardActiveTotalElectricalEnergy(forwardActiveTotalElectricalEnergy);
                powerdata.setTotalReverseActiveEnergy(totalReverseActiveEnergy);
                //根据报文中的sn去查询设备
                device = deviceMapper.selectByserialNumber(powerdata.getDeviceid());
                powerdata.setTableName(device.getTableName());
                powerdata.setDeviceName(device.getDeviceName());
                //seconds.substring(0,1).equals("1")判断秒的第一位是1
                Date date = new Date();
                int minutes = date.getMinutes();
                String seconds = date.getSeconds()+"";
                if(minutes%10==0){
                    if(device!=null){
                        if (device.getTransformerStatus()==1){
                        //if(device.getDeviceName().contains("变压器")){
                            IncomingCabinet incomingCabinet=new IncomingCabinet();
                            incomingCabinet.setDeviceId(device.getDeviceId());
                            incomingCabinet.setDeviceName(device.getDeviceName());
                            incomingCabinet.setSn(powerdata.getDeviceid());
                            incomingCabinet.setCreateTime(powerdata.getCreatetime());
                            incomingCabinet.setForwardActiveTotalElectricalEnergy(powerdata.getForwardActiveTotalElectricalEnergy());
                            incomingCabinet.setPt(powerdata.getPt());
                            incomingCabinet.setProjectId(device.getProjectId());
                            incomingCabinet.setIa(powerdata.getIa());
                            incomingCabinet.setIb(powerdata.getIb());
                            incomingCabinet.setIc(powerdata.getIc());
                            incomingCabinet.setUa(powerdata.getUa());
                            incomingCabinet.setUb(powerdata.getUb());
                            incomingCabinet.setUc(powerdata.getUc());
                            incomingCabinet.setPtf(powerdata.getPtf());
                            incomingCabinet.setPtn(powerdata.getPtn());
                            incomingCabinet.setAreaId(device.getAreaId());
                            incomingCabinet.setAreaName(device.getAreaName());
                            incomingCabinet.setProjectId(device.getProjectId());
                            incomingCabinet.setProjectName(device.getNavId());
                            incomingCabinet.setPowerRoomId(device.getPowerRoomId());
                            incomingCabinet.setPowerRoomName(device.getPowerRoomName());
                            incomingCabinet.setPtin(powerdata.getPtin());
                            int i=incomingCabinetMapper.addIncomingCabinet(incomingCabinet);
                    }
                }
                res = powerdataMapper.insertSelective(powerdata);
            }
        }
        if(device!=null){
            redisTemplate.opsForValue().set(device.getSerialNumber(),powerdata,61, TimeUnit.SECONDS);
        }

        if (res > 0) {
            return Resp.success();
        } else {
            return Resp.fail();
        }

    }

    @Override

    public Resp GetPowerData(String navId) {
        if (navId == null && navId == "") {
            return Resp.fail("参数错误");
        }
        String sn = deviceMapper.selectSnBydeviceId(navId);
        if (sn == null) {
            return Resp.fail("参数错误或无此设备");
        }
        List list = powerdataMapper.getpowerData(sn);
        System.out.println("数据监测中");
        if (list.size() != 0) {
            return Resp.success(list);
        } else {
            System.out.println("未获取到数据");
            return Resp.fail();
        }
    }

//    @Override
//    public Map warn() {
//        return null;
//    }

    @Override
//    @Scheduled(cron = "0/5 * *  * * ? ")
    public Resp warn()   {
        SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
        System.out.println("正在执行报警监测：" + sm.format(new Date()));
        List snList = deviceMapper.selectSnList();
        if (snList.size() < 1) {
            return Resp.fail();
        }
//        for (int j = 0; j <3 ; j++) {
            for (int i = 0; i < snList.size(); i++) {
                String sn = (String) snList.get(i);

                List dataList = powerdataMapper.getpowerData2Min(sn);
                if (dataList.size() == 0 ) {
                    String falut = "通讯中断";
                    String navId =deviceMapper.selectByserialNumber(sn).getDeviceId();
                    System.out.println(snList.get(i)+"通讯中断"+new Date());

                    int res = orderDeliveryMapper.selectBydeviceId(navId);
                    if (res == 0){
                        System.out.println(snList.get(i)+"报警信息"+new Date());
                        orderDeliveryService.addIncidentRecordOrderDelivery(navId,falut);

                    }

                }
            }
//        }

        return Resp.fail();
    }
    //每天十点定时忽略工单
    @Scheduled(cron ="0 0 10 * * ?")
    public Resp ResetOrderStatues(){
        int res = orderDeliveryMapper.resetOrderStatues();

    if (res > 0){
        System.out.println("忽略工单成功");
        return Resp.success();
    }else{
        System.out.println("忽略工单失败");
        return Resp.fail();
    }

    }

    /*<!--查詢所有设备-->*/
    @Override
    public PageInfo<Powerdata> queryProwerAllDevices(Integer pageNum,Integer pageSize,String projectId, String time) {
        Project project = projectMapper.queryProjectTableName(projectId);
        List<Powerdata> list =powerdataMapper.queryProwerAllDevices(pageNum,pageSize,time,project.getTableName());
        return new PageInfo<>(list);
    }

    /*<!--所有设备数据导出-->*/
    @Override
    public List<Powerdata> queryPowerAllExport(String projectId, String time) {
        Project project = projectMapper.queryProjectTableName(projectId);
        Integer i = deviceMapper.queryPowerPage(projectId);
        return powerdataMapper.queryPowerAllExport(i,time,project.getTableName());
    }

    @Override
    public List<Powerdata> queryPowerData(String deviceId, String time, String dataType ,String minute) {
        Device device = deviceMapper.selectByserialNumber(deviceId);
        if(minute.equals("0")){
            List<Powerdata> list =powerdataMapper.queryPowerData(deviceId,time,dataType,device.getTableName());
            return list;
        }
        return powerdataMapper.queryPowerDataHalfhour(deviceId,time,dataType,device.getTableName());
    }

    @Override
    public List<Powerdata> queryYesterday(String deviceId, String time, String dataType) {
        return powerdataMapper.queryYesterday(deviceId,time,dataType);
    }

    @Override
    public List<PowerNewData> getPowerNewData(String deviceId,String type) {

        PowerNewData powerNewData=null;
        String s="";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<PowerNewData> list=new ArrayList<>();
        if(redisTemplate.opsForValue().get(deviceId)!=null){
            s =redisTemplate.opsForValue().get(deviceId).toString();
        }
        Device device = deviceMapper.selectByserialNumber(deviceId);


        if(type.equals("1")){  // 电压
            // Ua
            powerNewData = powerdataMapper.getPowerUaDataByDeviceId(deviceId,device.getTableName());
            if(powerNewData!=null){
                powerNewData.setName("A相电压");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("ua"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }
            // Ub
            powerNewData = powerdataMapper.getPowerUbDataByDeviceId(deviceId,device.getTableName());
            if(powerNewData!=null){
                powerNewData.setName("B相电压");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("ub"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }

            // Uc
            powerNewData = powerdataMapper.getPowerUcDataByDeviceId(deviceId,device.getTableName());
            if(powerNewData!=null){
                powerNewData.setName("C相电压");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("ub"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }

            // Uab
            powerNewData = powerdataMapper.getPowerUabDataByDeviceId(deviceId,device.getTableName());
            if (powerNewData!=null){
                powerNewData.setName("AB线电压");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("uab"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }

            // Ubc
            powerNewData = powerdataMapper.getPowerUbcDataByDeviceId(deviceId,device.getTableName());
            if(powerNewData!=null){
                powerNewData.setName("BC线电压");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("ubc"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }

            // Uca
            powerNewData = powerdataMapper.getPowerUcaDataByDeviceId(deviceId,device.getTableName());
            if(powerNewData!=null){
                powerNewData.setName("CA线电压");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("uca"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }

        }else if(type.equals("2")){  // 电流
            //Ia
            powerNewData = powerdataMapper.getPowerIaDataByDeviceId(deviceId,device.getTableName());
            if(powerNewData!=null){
                powerNewData.setName("A相电流");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("ia"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }

            //Ib
            powerNewData = powerdataMapper.getPowerIbDataByDeviceId(deviceId,device.getTableName());
            if(powerNewData!=null){
                powerNewData.setName("B相电流");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("ib"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }

            //Ic
            powerNewData = powerdataMapper.getPowerIcDataByDeviceId(deviceId,device.getTableName());
            if(powerNewData!=null){
                powerNewData.setName("C相电流");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("ic"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }

        }else if(type.equals("3")){ //功率
            // Pt 总有功功率
            powerNewData = powerdataMapper.getPowerPtDataByDeviceId(deviceId,device.getTableName());
            if(powerNewData!=null){
                powerNewData.setName("有功功率");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("pt"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }

            // Ptn 总无功功率
            powerNewData = powerdataMapper.getPowerPtnDataByDeviceId(deviceId,device.getTableName());
            if(powerNewData!=null){
                powerNewData.setName("无功功率");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("ptn"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }

            // Ptin 总视在功率
            powerNewData = powerdataMapper.getPowerPtinDataByDeviceId(deviceId,device.getTableName());
            if(powerNewData!=null){
                powerNewData.setName("视在功率");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("ptin"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }

            // Ptf 总功率因数
            powerNewData = powerdataMapper.getPowerPtfDataByDeviceId(deviceId,device.getTableName());
            if(powerNewData!=null){
                powerNewData.setName("功率因数");
                if(StringUtils.isNotBlank(s)){
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    powerNewData.setNewData(jsonObject.getFloat("ptf"));
                    if(powerNewData.getNewData()>powerNewData.getMaxData()){
                        powerNewData.setMaxData(powerNewData.getNewData());
                        powerNewData.setMaxTime(simpleDateFormat.format(new Date()));
                    }
                    if(powerNewData.getNewData()<powerNewData.getMinData()){
                        powerNewData.setMinData(powerNewData.getNewData());
                        powerNewData.setMinTime(simpleDateFormat.format(new Date()));
                    }
                }
                list.add(powerNewData);
            }

        }else if (type.equals("4")){ //电能
            // forwardActiveTotalElectricalEnergy 正向有功电能
            powerNewData=new PowerNewData();
            powerNewData.setName("正向有功总电能");
            if(StringUtils.isNotBlank(s)){
                JSONObject jsonObject = JSONObject.parseObject(s);
                powerNewData.setNewData(jsonObject.getFloat("forwardActiveTotalElectricalEnergy"));
            }
            list.add(powerNewData);
        }


        return list;
    }


    //@Scheduled(cron = "01 52 23 * * ?")
    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0 0/5 * * * ?")
    public void insertPower() {
        List<Device> list = deviceMapper.getAll();
        for (Device device : list) {
            Powerdata powerData=powerdataMapper.queryPowerDataDay(device.getTableName(),device.getSerialNumber());
            if(powerData!=null){
                powerData.setTableName("powerdata_timing");
                powerData.setProject_id(device.getProjectId());
                powerData.setArea_id(device.getAreaId());
                powerData.setPower_room_id(device.getPowerRoomId());
                int res = powerdataMapper.insertSelective(powerData);
            }
        }
        List<TemperatureDevice>temperatureDevices = temperatureDeviceMapper.getTemperatureDeviceAll();
        for (TemperatureDevice temperatureDevice : temperatureDevices) {
            TemperatureData temperatureData = temperatureDataMapper.queryTemperatureData(temperatureDevice.getTableName(),temperatureDevice.getSerialNumber());
            System.out.println(temperatureData);
            if(temperatureData!=null){
                temperatureData.setTableName("powerdata_timing");
                temperatureData.setProjectId(temperatureDevice.getProjectId());
                temperatureData.setAreaId(temperatureDevice.getAreaId());
                temperatureData.setPowerRoomId(temperatureDevice.getPowerRoomId());
                int res = temperatureDataMapper.insertTemperatureData(temperatureData);
            }
        }
    }






    @Override
    public void insertPowers() {
        List<Device> list = deviceMapper.getAll();
        for (Device device : list) {
            Powerdata powerData=powerdataMapper.queryPowerDataDay(device.getTableName(),device.getSerialNumber());
            if(powerData!=null){
                powerData.setTableName("powerdata_timing");
                powerData.setProject_id(device.getProjectId());
                int res = powerdataMapper.insertSelective(powerData);
            }
        }
        List<TemperatureDevice>temperatureDevices = temperatureDeviceMapper.getTemperatureDeviceAll();
        for (TemperatureDevice temperatureDevice : temperatureDevices) {
            TemperatureData temperatureData = temperatureDataMapper.queryTemperatureData(temperatureDevice.getTableName(),temperatureDevice.getSerialNumber());
            System.out.println(temperatureData);
                if(temperatureData!=null){
                temperatureData.setTableName("powerdata_timing");
                temperatureData.setProjectId(temperatureDevice.getProjectId());
                int res = temperatureDataMapper.insertTemperatureData(temperatureData);
                    System.out.println(res);
            }
        }
    }

    @Override
    public List<Powerdata> getPowerData(String serialNumber, String time) {
        Device device = deviceMapper.getDeviceBySerialNumber(serialNumber);
        if (device!=null){
            if(StringUtils.isNotBlank(device.getTableName())){
                List<Powerdata>  list = powerdataMapper.getPowerDataBySerialNumber(serialNumber,time,device.getTableName());
                return list;
            }
        }
        return null;
    }


    /**
     * 首页电量历史数据
     * @param startTime
     * @param endTime
     * @param token
     * @return
     */
    @SneakyThrows
    @Override
    public List<List<PowerConsume>> getPowerDataByMonth(String startTime, String endTime,String token) throws ParseException {
        List<List<PowerConsume>> powerConsumeList=new ArrayList<>();
        SysUser user = sysUserMapper.getUserByToken(token);
        if (user!=null){
            Project project = projectMapper.queryProjectByProId(user.getProjectId().toString());
            if(project.getPowerDaraFlag().equals("1")){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Calendar calendar  =   Calendar.getInstance();
                if (calendar.get(Calendar.DAY_OF_MONTH)<=simpleDateFormat.parse(endTime).getDate()){
                    calendar.setTime(simpleDateFormat.parse(endTime)); //需要将date数据转移到Calender对象中操作
                    calendar.add(calendar.DATE, 1);//把日期往后增加n天.正数往后推,负数往前移动
                    Date time = calendar.getTime();//这个时间就是日期往后推一天的结果
                    List<PowerConsume> powerConsumes = powerdataMapper.getPowerDataByMonth(startTime,simpleDateFormat.format(time),project.getProjectId(),project.getTableName());

                    if(powerConsumes.size()>0){
                        //根据地区项目配电房查询设备的设备号
                        List<String> deviceIdList = deviceMapper.getDeviceId(project.getProjectId());
                        for(String deviceId:deviceIdList){
                            List<PowerConsume> list=new ArrayList();
                            for (PowerConsume powerConsume:powerConsumes){
                                if(deviceId.equals(powerConsume.getDeviceId())){
                                    powerConsume.setTime(powerConsume.getTime().substring(powerConsume.getTime().indexOf("-")+1));
                                    list.add(powerConsume);
                                }

                            }
                            if(list.size()>0){
                                powerConsumeList.add(list);
                            }

                        }
                        for (List<PowerConsume> list:powerConsumeList){
                            for (int i=0;i<list.size(); i++){
                                PowerConsume powerConsume = list.get(i);
                                if (i+1<list.size()){
                                    powerConsume.setForwardActiveTotalElectricalEnergy(list.get(i+1).getMinForwardActiveTotalElectricalEnergy()-powerConsume.getMinForwardActiveTotalElectricalEnergy());
                                }else{
                                    powerConsume.setForwardActiveTotalElectricalEnergy(powerConsume.getMaxForwardActiveTotalElectricalEnergy()-powerConsume.getMinForwardActiveTotalElectricalEnergy());
                                }
                            }
                        }
                    }

                }else{
                    calendar.setTime(simpleDateFormat.parse(endTime)); //需要将date数据转移到Calender对象中操作
                    calendar.add(calendar.DATE, 2);//把日期往后增加n天.正数往后推,负数往前移动
                    Date time = calendar.getTime();//这个时间就是日期往后推一天的结果
                    List<PowerConsume> powerConsumes = powerdataMapper.getPowerDataByMonth(startTime,simpleDateFormat.format(time),project.getProjectId(),project.getTableName());

                    if(powerConsumes.size()>0){
                        //根据地区项目配电房查询设备的设备号
                        List<String> deviceIdList = deviceMapper.getDeviceId(project.getProjectId());
                        for(String deviceId:deviceIdList){
                            List<PowerConsume> list=new ArrayList();
                            for (PowerConsume powerConsume:powerConsumes){
                                if(deviceId.equals(powerConsume.getDeviceId())){
                                    powerConsume.setTime(powerConsume.getTime().substring(powerConsume.getTime().indexOf("-")+1));
                                    list.add(powerConsume);
                                }

                            }
                            if(list.size()>0){
                                powerConsumeList.add(list);
                            }

                        }
                        for (List<PowerConsume> list:powerConsumeList){
                            for (int i=0;i<list.size(); i++){
                                PowerConsume powerConsume = list.get(i);
                                if (i+1<list.size()){
                                    powerConsume.setForwardActiveTotalElectricalEnergy(list.get(i+1).getMinForwardActiveTotalElectricalEnergy()-powerConsume.getMinForwardActiveTotalElectricalEnergy());
                                }else{
                                    list.remove(i);
                                }
                            }
                        }
                    }


                }
            }else{
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Calendar calendar  =   Calendar.getInstance();
                if (calendar.get(Calendar.DAY_OF_MONTH)<=simpleDateFormat.parse(endTime).getDate()){
                    calendar.setTime(simpleDateFormat.parse(endTime)); //需要将date数据转移到Calender对象中操作
                    calendar.add(calendar.DATE, 1);//把日期往后增加n天.正数往后推,负数往前移动
                    Date time = calendar.getTime();//这个时间就是日期往后推一天的结果

                    //根据地区id项目id配电房id查询设备
                    List<PowerConsume> powerConsumes = temperatureDataMapper.getPowerDataByMonth(startTime,simpleDateFormat.format(time),project.getProjectId(),project.getTemperatureDataTableName());
                    if(powerConsumes.size()>0){
                        //根据地区项目配电房查询设备的设备号
                        List<String> deviceIdList = temperatureDeviceMapper.getDeviceId(null, project.getProjectId(), null);
                        for(String deviceId:deviceIdList){
                            List<PowerConsume> list=new ArrayList();
                            for (PowerConsume powerConsume:powerConsumes){
                                if(deviceId.equals(powerConsume.getDeviceId())){
                                    powerConsume.setTime(powerConsume.getTime().substring(powerConsume.getTime().indexOf("-")+1));
                                    list.add(powerConsume);
                                }

                            }
                            if(list.size()>0){
                                powerConsumeList.add(list);
                            }

                        }
                        for (List<PowerConsume> list:powerConsumeList){
                            for (int i=0;i<list.size(); i++){
                                PowerConsume powerConsume = list.get(i);
                                if (i+1<list.size()){
                                    powerConsume.setForwardActiveTotalElectricalEnergy(list.get(i+1).getMinForwardActiveTotalElectricalEnergy()-powerConsume.getMinForwardActiveTotalElectricalEnergy());
                                }else{
                                    powerConsume.setForwardActiveTotalElectricalEnergy(powerConsume.getMaxForwardActiveTotalElectricalEnergy()-powerConsume.getMinForwardActiveTotalElectricalEnergy());
                                }
                            }
                        }
                    }

                }else{
                    calendar.setTime(simpleDateFormat.parse(endTime)); //需要将date数据转移到Calender对象中操作
                    calendar.add(calendar.DATE, 2);//把日期往后增加n天.正数往后推,负数往前移动
                    Date time = calendar.getTime();//这个时间就是日期往后推一天的结果

                    //根据地区id项目id配电房id查询设备
                    List<PowerConsume> powerConsumes = temperatureDataMapper.getPowerDataByMonth(startTime,simpleDateFormat.format(time),project.getProjectId(),project.getTemperatureDataTableName());
                    if(powerConsumes.size()>0){
                        //根据地区项目配电房查询设备的设备号
                        List<String> deviceIdList = temperatureDeviceMapper.getDeviceId(null, project.getProjectId(), null);
                        for(String deviceId:deviceIdList){
                            List<PowerConsume> list=new ArrayList();
                            for (PowerConsume powerConsume:powerConsumes){
                                if(deviceId.equals(powerConsume.getDeviceId())){
                                    powerConsume.setTime(powerConsume.getTime().substring(powerConsume.getTime().indexOf("-")+1));
                                    list.add(powerConsume);
                                }

                            }
                            if(list.size()>0){
                                powerConsumeList.add(list);
                            }

                        }
                        for (List<PowerConsume> list:powerConsumeList){
                            for (int i=0;i<list.size(); i++){
                                PowerConsume powerConsume = list.get(i);
                                if (i+1<list.size()){
                                    powerConsume.setForwardActiveTotalElectricalEnergy(list.get(i+1).getMinForwardActiveTotalElectricalEnergy()-powerConsume.getMinForwardActiveTotalElectricalEnergy());
                                }else{
                                    list.remove(i);
                                }
                            }
                        }
                    }


                }
            }

            return  powerConsumeList;
        }

        return null;


    }
}
